package com.jiazhong.spring.rocketmq.普通消息.消费.集群消息;

import lombok.SneakyThrows;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.protocol.heartbeat.MessageModel;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class 广播消息消费2 {
    @SneakyThrows
    public static void main(String[] args) {
        // 1.创建消费者 Consumer，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group_a");
        // 2.指定 NameSrv 地址
        consumer.setNamesrvAddr("124.220.170.254:9876");
        // 3. 设置集群还是广播
        consumer.setMessageModel(MessageModel.BROADCASTING);
        // 4.订阅主题 Topic 和 Tag
        consumer.subscribe("TopicA", "async");
        // 5.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                try {
                    System.out.println("当有订阅的主题和标签有新消息时，自动执行这里的代码");
                    //System.out.println(context.getMessageQueue());
                    //System.out.println(context.getAckIndex());
                    //System.out.println(context);
                    //System.out.println("收到的消息是：");
                    for (MessageExt msg : list) {
                        String topic = msg.getTopic();
                        String tags = msg.getTags();
                        String body = new String(msg.getBody(), StandardCharsets.UTF_8);
                        System.out.println(list.size() + "..." + body);
                    }
                } catch (Exception e) {
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 6.启动消费者 Consumer
        consumer.start();
    }
}
